package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.feign.SeckillFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.ItemSaleAttrVo;
import com.atguigu.gulimall.product.vo.SeckillVo;
import com.atguigu.gulimall.product.vo.SkuItemVo;
import com.atguigu.gulimall.product.vo.SpuItemAttrGroup;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Lazy
    @Resource
    SeckillFeignService seckillFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    //sku检索

    @Override
    public PageUtils queryPageByConditions(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper= new QueryWrapper<>();

        String key =(String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(item->{
                item.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        String brandId =(String) params.get("brandId");
        if(StringUtils.isNotEmpty(brandId) &&!"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotEmpty(catelogId) &&!"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        String min =(String) params.get("min");
        if(StringUtils.isNotEmpty(min)){
            wrapper.ge("price",min);
        }

        String max = (String) params.get("max");
        if(StringUtils.isNotEmpty(max)){
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if(bigDecimal.compareTo(BigDecimal.ZERO)==1){
                    wrapper.le("price",max);
                }
            }catch (Exception e){
                System.out.println(e.getCause());

            }

        }

        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> spu_id = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        return spu_id;
    }

    @Autowired
    private SkuImagesService skuimagesService;

   @Autowired
   private SpuInfoDescService spuInfoDescService;

   @Autowired
   private AttrGroupService attrGroupService;

   @Autowired
   private SkuSaleAttrValueService skuSaleAttrValueService;

   @Autowired
   private ThreadPoolExecutor executor;
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> info = CompletableFuture.supplyAsync(() -> {
            //1、sku基本信息的获取  pms_sku_info
            SkuInfoEntity skuInfoEntity = this.getById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, executor);

        //3、获取spu的销售属性组合-> 依赖1 获取spuId

        CompletableFuture<Void> sale = info.thenAcceptAsync((res) -> {
            List<ItemSaleAttrVo> skuItemVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());

            skuItemVo.setSaleAttr(skuItemVos);
        }, executor);
        //4、获取spu的介绍-> 依赖1 获取spuId

        CompletableFuture<Void> spu = info.thenAcceptAsync((res) -> {

            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);

        });


        //5、获取spu的规格参数信息-> 依赖1 获取spuId catalogId
        CompletableFuture<Void> guige = info.thenAcceptAsync((res) -> {
            List<SpuItemAttrGroup> attrGroups = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroups);
        }, executor);


        //2、sku的图片信息    pms_sku_images

        CompletableFuture<Void> image = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImagesEntities = skuimagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
            skuItemVo.setImages(skuImagesEntities);
        }, executor);


        // 6、秒杀商品的优惠信息

        CompletableFuture<Void> seckill = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuSeckillInfo(skuId);
            System.out.println(JSON.toJSONString(r));
            if (r.getCode() == 0) {
                Object to = r.get("to");
                String jsonString = JSON.toJSONString(to);
                SeckillVo seckillVo = JSON.parseObject(jsonString, SeckillVo.class);
                skuItemVo.setSeckillVo(seckillVo);
            }
        }, executor);


        //等待所有任务都完成
        CompletableFuture.allOf(sale,spu,guige,image,seckill).get();
        return skuItemVo;


    }

}